// 实名返回错误
const authorStatusError = -1;
// 需要实名
const goIdentify = 1;
// 需要风测
const goRisk = 2;
// 需要签名
const goSign = 3;
// 无需实名风测
const dontIdentifyAndRisk = 4;
// 接口超时
const ajaxTimeOut = 3000;
const statMap = {
  1: 'zscphg.realname',  
  2: 'zscphg.risktest',  
  3: 'zscphg.usersign',  
}
window.Vue.component('riskvalidatepopup', {
  template: `
  <div class="risk-dialog" v-if="needRisk">
  <hxm-popup
    :show="needRisk"
    class="risk-overlay"
    :popup-style="{ width: '5.6rem', height: 'auto !mportant', borderRadius: '0.08rem' }"
  >
    <div class="dialog-wrap" v-if="riskStatusText">
      <div class="dialog-head">
        <span class="dialog-title"
          >根据国家监管要求，使用本产品前需要完成
          <span @click="goRisk" class="dialog-tip">{{ riskStatusText }}</span>
        </span>
      </div>
      <div class="agree-protocol">
        <i
          :class="checkProtocol ? 'icon-check' : 'icon-nocheck'"
          @click="checkProtocolHandle"
        ></i>
        我已阅读并同意<span class="book" @click="goProtocol">《投资服务协议》</span>
      </div>
      <div class="dialog-button-group">
        <div class="dialog-button left" @click="goBack('auto')">取消</div>
        <div class="dialog-button right" @click="goRisk">{{ confirmButton }}</div>
      </div>
    </div>
    <div class="loading-dialog" v-else>
      <hxm-loading class="loading-tag"></hxm-loading>
    </div>
  </hxm-popup>
</div>`,
  data() {
    return {
      needRisk: false,
      riskStatusText: null,
      confirmButton: null,
      riskPage: null,
      riskStatus: null,
      checkProtocol: false,
    };
  },
  created() {
    this.authorDialog();
    // 注册返回监听，如果进入过实名，则返回退回决策
    this.notifyBack();
  },
  methods: {
    // 关闭弹窗解锁body滚动
    closeRiskPopup(){
      this.needRisk = false;
      window.document.body.style.position = 'relative';
      window.document.body.style.top = 0;
      window.document.body.style.left = 0;
    },
    // 获取实名状态 -1: 查询失败；1:未实名或实名未通过；2:未风测或风测未通过；3:需要签名；4: 通过或无需校验；
    getRiskAssessment(callback) {
      // 实名不通过
      const noPassIdentifyState = -1;
      // 符合匹配
      const needSign = 1;
      // 符合不匹配
      const riskQualifiedStatus = 2;
      // 不符合不匹配
      const noMatch = 3;
      // 失信人
      const dishonest = 4;
      this.getSendStatus(isGiving => {
        if (!isGiving) {
          return dontIdentifyAndRisk;
        }
        this.needRisk = true;
        window.$.ajax({
          type: 'get',
          url: window.hxmConfig.riskStatusApi,
          dataType: 'json',
          data: {
            pid: '269',
          },
          xhrFields: {
            withCredentials: true,
          },
          cache: false,
          timeout: ajaxTimeOut,
          success: res => {
            if (!res || !res.data || +res.errorCode !== 0) {
              return authorStatusError;
            }
            const { authorizeState, authorizeType, risktestState, productProperState, isProductProperState } = res.data;
            // 实名不通过
            const identifyNoPass = !authorizeState || +authorizeType === noPassIdentifyState;
            // 风测不通过(不显示、不符合不匹配、不守信、符合不匹配)
            const passRiskState = [0, noMatch, dishonest, riskQualifiedStatus];
            const riskNoPass = !risktestState || passRiskState.indexOf(+productProperState) > -1;
            // 无签名需要签名
            const noSign = risktestState && +productProperState === needSign && !isProductProperState;
            const riskStatus = this.identifyAndRiskStatusMap(identifyNoPass, riskNoPass, noSign);
            this.riskStatus = riskStatus;
            callback && callback(riskStatus);
            return riskStatus;
          },
          error: () => {
            this.closeRiskPopup();
          },
        });
        return isGiving;
      });
    },

    // 判断产品是不是赠送
    getSendStatus(callback) {
      window.$.ajax({
        type: 'get',
        url: window.hxmConfig.judgeSendApi,
        dataType: 'json',
        data: {
          sid: '269',
        },
        xhrFields: {
          withCredentials: true,
        },
        cache: false,
        timeout: ajaxTimeOut,
        success: res => {
          let isGiving = false;
          if (!res || !res.data || +res.status_code !== 0) {
            callback && callback(isGiving);
            return true;
          }
          isGiving = res.data.need_compliance === 1;
          callback && callback(isGiving);
          return isGiving;
        },
        error: () => {
          this.closeRiskPopup();
        },
      });
    },

    // 勾选用户须知
    checkProtocolHandle() {
      this.checkProtocol = !this.checkProtocol;
    },

    // 实名状态响应
    identifyAndRiskStatusMap(identifyNoPass, riskNoPass, noSign) {
      let status = null;
      if (identifyNoPass) {
        status = goIdentify;
      } else if (riskNoPass) {
        status = goRisk;
      } else if (noSign) {
        status = goSign;
      } else {
        status = dontIdentifyAndRisk;
      }
      return status;
    },

    goRisk() {
      if (!this.checkProtocol) {
        this.$dialog({
          content: '为了保障您的权益，使用增值服务需同意《投资服务协议》',
          btns: [
            {
              text: '再看看',
            },
            {
              text: '同意',
              callback: () => {
                this.checkProtocolHandle();
              },
            },
          ],
        });
        return;
      }
      window.thsStats.clickStat('index', `${statMap[this.riskStatus]}.click`);
      window.location.href = window._hxmFormatUrl(this.riskPage);
    },

    // 实名状态弹窗
    authorDialog(skipAgreement = 1) {
      const messageAlert = {
        1: '实名认证',
        2: '风险测评',
        3: '用户签名',
      };
      this.getRiskAssessment(authorStatus => {
        const riskParams = {
          skipAgreement,
          sid: '269',
          isGiving: 1,
          url: window.encodeURIComponent(this.appendUrlParams(window.hxmConfig.currentFromRiskPage)),
        };
        this.riskPage = this.appendUrlParams(window.hxmConfig.riskAssessmentPage, riskParams);
        if (skipAgreement && +authorStatus === dontIdentifyAndRisk || +authorStatus === authorStatusError) {
          this.closeRiskPopup();
          return;
        }
        window.thsStats.clickStat('index', `${statMap[this.riskStatus]}.show`);
        this.needRisk = true;
        this.riskStatusText = messageAlert[authorStatus];
        this.confirmButton = messageAlert[authorStatus];
      });
    },

    // 跳转用户须知页
    goProtocol() {
      const params = {
        sid: '269',
        isGiving: 1,
      };
      const protocolUrl = this.appendUrlParams(window.hxmConfig.protocolPage, params);
      window.location.href = window._hxmFormatUrl(protocolUrl);
    },

    /**
     * 链接参数拼接工具方法
     * @param {string} url
     * @param {object} params
     * @returns url
     */
    appendUrlParams(url, params) {
      if (!url) {
        return url;
      }
      const link = url.indexOf('?') > -1 ? '&' : '?';
      let res = url + link;
      for (const key in params) {
        if (params.hasOwnProperty(key) && params[key]) {
          res += `${key  }=${  params[key]}&`;
        }
      }
      return res && res.slice(0, res.length - 1);
    },

    // 开启返回监听拦截
    notifyBack() {
      const isRiskBash = +window.getParam('isRiskBash') === 1;
      window.callNativeHandler('notifyWebHandleEvent', {
        method: 'detainNotify',
        type: '1',
      });
      // 返回跳回决策
      window.registerWebHandler('notifyWebHandleEvent', data => {
        if (data.method === 'detainNotify') {
          if (String(data.type) === '2') {
            window.callNativeHandler('goback', { type: 'component' });
            return;
          }
          if (isRiskBash) {
            this.goBack('juece');
          } else {
            this.goBack();
          }
        }
      });
    },

    // 跳转全面屏
    goFullScreen(link, color) {
      let url = '';
      let { protocol } = window.location;
      if (link.indexOf('://') > -1) {
        protocol = '';
      }
      // 判定客户端
      if (window.getPlatform() === 'gphone') {
        url = `client.html?action=ymtz^url=${protocol}${link}^webid=4222^mode=new`;
      } else {
        url = `client.html?action=ymtz^url=${protocol}${link}^webid=2305^showStatusBar=1`;
        // 组装黑夜白天数据
        if (color) {
          const theme = window.getCssStyle() === 'black' ? 'black' : 'white';
          const statusBarColor = theme === 'white' ? color.white : color.black;
          url = `client.html?action=ymtz^url=${protocol}${link}^webid=2305^showStatusBar=1^statusBarColor=${statusBarColor}`;
        }
      }
      window.location.href = url;
    },

    // 返回事件
    goBack(type){
      window.thsStats.clickStat('index', `${statMap[this.riskStatus]}.quxiao`);
      const autoGoJuece = type === 'auto' && +window.getParam('isRiskBash') === 1;
      if (type === 'juece' || autoGoJuece) {
        this.goFullScreen(window.hxmConfig.juecePage, {
          white: '#060606',
          black: '#020202',
        });
      } else {
        window.callNativeHandler('goback', {
          type: window.getPlatform() === 'iphone' ? 'webview' : 'webpage',
        });
      }
    },
  },
});
